package com.atguigu.hivemq.service.impl;

import com.atguigu.hivemq.config.PushCallBack;
import com.atguigu.hivemq.service.ComsumerService;
import com.atguigu.springcloud.config.Result;
import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.mqtt3.Mqtt3BlockingClient;
import com.hivemq.client.mqtt.mqtt3.Mqtt3Client;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author zhenyu
 *
 * @desc @Date 2022/10/11 14:43 @Version 1.0
 */
@Component
@Slf4j
public class ComsumerServiceImpl  implements ComsumerService {

  @Value("${mqtt.server.url}")
  private String url;
  @Value("${mqtt.server.port}")
  private int port;

  //  @PostConstruct //表示在项目开始的时候自动运行
  @Override
  public Result<Object> subscribe(String topic){

    Mqtt3BlockingClient client =
        Mqtt3Client.builder()
            .identifier(UUID.randomUUID().toString())
            .serverHost(url)
            .serverPort(port)
            .buildBlocking();

    client.connect();

    Map<String,Object> map = new HashMap<>();

    try {

      // 收到从test/#主题订阅的消息,#代表多个字符。
      client.toAsync()
            .subscribeWith()
            .topicFilter(topic)
            .qos(MqttQos.AT_LEAST_ONCE)
            .callback(new PushCallBack())
            .send();
    } catch (Exception e) {
      e.printStackTrace();
      client.disconnect();
    }
    return Result.success("消费成功");
  }
}
